package perform.criterion;

import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;

import perform.mappings.ClassMappings;
import perform.type.Type;

public class AbstractCriterion implements Criterion{
	
	protected StringBuilder builder;
	
	protected AbstractCriterion(StringBuilder builder){
		this.builder = builder;
	}
	
	@SuppressWarnings("unchecked")
	protected static String getValue(Object value){
		if(value == null){
			return "null";
		} else if(value instanceof Type){
			try {
				return getValue(ClassMappings.getIDField((Class<? extends Type>)value.getClass()).get(value));
			} catch (Exception e) {
				e.printStackTrace();
				return "null";
			}
		} else if(value instanceof Number){
			return value.toString();
		} else if(value instanceof Date){
			return "'" + new java.sql.Date(((Date)value).getTime()).toString() + "'";
		} else if(value instanceof Calendar){
			return "'" + new java.sql.Date(((Calendar)value).getTimeInMillis()).toString() + "'";
		} else if(value instanceof Time || value instanceof java.sql.Date || value instanceof Timestamp 
				|| value instanceof CharSequence || value instanceof Enum){
			return "'" + value.toString() + "'";
		} else if(value instanceof Character){
			return "'" + value + "'";
		} else if(value instanceof char[]){
			return "'" + String.valueOf((char[])value) + "'";
		} else if(value instanceof Character[]){
			String string = "'";
			Character[] chars = (Character[]) value;
			for (int i = 0; i < chars.length; i++) {
				string += chars[i];
			}
			return string + "'";
		} else {
			return "'" + value.toString() + "'" ;
		}
	}
	
	@Override
	public final String toString() {
		return builder.toString();
	}

}
